<!--
 * @Author: xuna
 * @Descripttion: 新增编辑投票活动
-->
<template>
  <div>
    <el-drawer
      :title="drawerTitle"
      :visible.sync="isOpenEdit"
      :direction="direction"
      :wrapper-closable="false"
      size="40%"
      :before-close="beforeClose"
      class="draw-panel"
    >
      <div v-loading="loading" class="detail-wrap">
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
          class="demo-ruleForm"
        >
          <div class="detail-label">基本信息</div>
          <div class="basic-detail">
            <el-form-item label="投票标题:" prop="voteTitle">
              <el-input
                v-model="ruleForm.voteTitle"
                placeholder="请输入报名标题"
                :disabled="activityStatus > 1 || activityStatus == 1"
                class="full-input"
              ></el-input>
            </el-form-item>
            <el-form-item prop="imgPath" label="活动头图:" class="upload-img">
              <uploadPicture
                :picture-path="ruleForm.imgPath"
                :is-disable="isDisable"
                @getImgPath="getImgPath"
              ></uploadPicture>
            </el-form-item>
            <el-form-item label="补充说明:" prop="voteExplain">
              <el-input
                v-model="ruleForm.voteExplain"
                type="textarea"
                :autosize="{ minRows: 3 }"
                resize="none"
                maxlength="500"
                :disabled="activityStatus > 1"
                show-word-limit
                placeholder="请输入补充说明"
              ></el-input>
            </el-form-item>

            <el-form-item label="截止时间:" prop="voteEndTime">
              <el-col class="vote-time">
                <el-date-picker
                  v-model="ruleForm.voteEndTime"
                  type="datetime"
                  placeholder="请选择投票截止时间"
                  :disabled="activityStatus > 1"
                  :picker-options="voteEndOption"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  prefix-icon="null"
                ></el-date-picker>
                <i class="el-icon-caret-bottom"></i>
              </el-col>
            </el-form-item>
            <el-form-item label="选项设置:" prop="optionset">
              <div class="option-list">
                <span v-for="(item, index) in optionList" :key="index" class="option-col">
                  {{ item }}
                  <i
                    v-if="activityStatus == 0"
                    class="el-icon-close"
                    @click="deleteOption(item, index)"
                  ></i>
                </span>
              </div>
              <el-row class="option-row">
                <el-input
                  v-model="ruleForm.optionset"
                  :disabled="activityStatus > 0"
                  placeholder="请输入选项"
                  class="full-input"
                ></el-input>
                <span
                  v-if="activityStatus == 0"
                  class="add-btn"
                  @click="addOption(ruleForm.optionset)"
                >
                  添加
                </span>
              </el-row>
            </el-form-item>
          </div>
          <div class="detail-label">其他设置</div>
          <el-form-item label="投票选项：" prop="voteType" class="jurisdType">
            <el-checkbox-group v-model="ruleForm.voteType" @change="ladderChange">
              <el-checkbox label="单选投票" :disabled="activityStatus > 1"></el-checkbox>
              <el-checkbox label="多选投票" :disabled="activityStatus > 1"></el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <el-form-item class="save-btn">
            <el-button
              class="settbtn"
              :disabled="activityStatus > 1"
              @click="resetForm('ruleForm')"
            >
              取消
            </el-button>
            <el-button
              class="settbtn savebtn"
              :disabled="activityStatus > 1"
              type="primary"
              @click="submitForm('ruleForm')"
            >
              确认并提交
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>

<script>
  import { voteAdd, checkVoteDetail, voteEdit } from '@/api/votesign';
  import uploadPicture from './uploadPicture';
  import vFilter from '@/filters/index';
  export default {
    components: { uploadPicture },
    props: {
      voteRow: {
        type: Object,
        default() {
          return {};
        },
      },
      isOpenEdit: {
        type: Boolean,
        required: true,
      },
      isEdit: {
        type: Boolean,
        required: true,
      },
    },
    data() {
      return {
        direction: 'rtl',
        ruleForm: {
          voteTitle: '',
          voteEndTime: null,
          voteType: [],
          voteExplain: '',
          optionset: '',
          imgPath: '',
        },
        rules: {
          voteTitle: [
            { required: true, message: '请输入报名标题', trigger: 'blur' },
            { min: 0, max: 30, message: '长度在 0 到 30 个字符', trigger: 'blur' },
          ],
          voteEndTime: [{ required: true, message: '请选择投票截止时间', trigger: 'blur' }],
          voteType: [{ required: true, message: '请选择投票选项', trigger: 'blur' }],
          optionset: [{ required: true, message: '请输入选项', trigger: 'blur' }],
          imgPath: [{ required: true, message: '请上传活动头图', trigger: 'blur' }],
        },
        optionList: [],
        drawerTitle: '',
        voteEndOption: {
          disabledDate: time => {
            return time.getTime() < Date.now() - 8.64e7 || time.getTime() > 1609344000000;
          },
        },
        activityStatus: 0,
        isDisable: false,
        loading: false,
      };
    },

    watch: {
      voteRow(newDtat) {
        console.log(newDtat);
        if (newDtat) {
          this.initVote(newDtat && this.isEdit);
        }
      },
      optionList(val) {
        if (!val.length) {
          this.rules = Object.assign(this.rules, {
            optionset: [{ required: true, message: '请输入选项', trigger: 'blur' }],
          });
        } else {
          delete this.rules.optionset;
        }
      },
    },
    activated() {},
    methods: {
      initVote(val) {
        if (val) {
          this.loading = true;
          this.drawerTitle = '编辑投票活动';
          try {
            checkVoteDetail({ id: this.voteRow.id }).then(res => {
              this.loading = false;
              if (res.status == 200) {
                console.log(res);
                let data = res.data;
                this.activityStatus = res.data.activityStatus;
                this.isDisable = this.activityStatus > 1;
                this.ruleForm = {
                  voteTitle: data.voteTitle,
                  voteEndTime: data.voteEndTime,
                  voteType: data.voteOption == 1 ? ['单选投票'] : ['多选投票'],
                  voteExplain: data.voteExplain,
                  imgPath: data.headImgs ? data.headImgs : '',
                };
                this.optionList = data.optionList.map(val => {
                  return val.voteOption;
                });
              }
            });
          } catch (error) {
            this.loading = false;
          }
        } else {
          this.drawerTitle = '新增投票活动';
          this.activityStatus = 0;
          this.isDisable = false;
          this.ruleForm = {
            voteTitle: '',
            voteEndTime: null,
            voteType: [],
            voteExplain: '',
            optionset: '',
          };
          this.$set(this.ruleForm, 'imgPath', '');
          this.optionList = [];
        }
      },
      beforeClose() {
        this.$emit('closeDrawer', false);
      },
      ladderChange() {
        if (this.ruleForm.voteType.length > 1) {
          this.ruleForm.voteType.shift();
        }
      },
      getImgPath(val) {
        this.ruleForm.imgPath = val;
      },
      addOption(val) {
        if (val) {
          this.optionList.push(val);
          this.ruleForm.optionset = '';
        }
      },
      deleteOption(val, index) {
        this.optionList.splice(index, 1);
      },
      submitForm(formName) {
        this.$refs[formName].validate(valid => {
          console.log(valid);
          if (valid) {
            if (this.ruleForm.optionset) {
              this.optionList.push(this.ruleForm.optionset);
            }
            if (new Date(this.ruleForm.voteEndTime).getTime() < new Date().getTime()) {
              return this.$message.warning('截止时间不能小于当前时间');
            }
            let objData = {
              voteTitle: this.ruleForm.voteTitle,
              voteStartTime: vFilter.timeFormat(new Date().getTime()),
              voteEndTime: this.ruleForm.voteEndTime,
              voteExplain: this.ruleForm.voteExplain,
              voteOption: this.ruleForm.voteType[0].includes('单选') ? 1 : 2,
              options: this.optionList,
              headImgs: this.ruleForm.imgPath,
            };
            console.log(this.ruleForm, '-------ruleForm');
            console.log(objData, '------------objData');
            this.loading = true;
            if (this.isEdit) {
              // 编辑
              objData = Object.assign(objData, {
                id: this.voteRow.id,
                version: this.voteRow.version,
              });
              try {
                voteEdit(objData).then(res => {
                  this.loading = false;
                  if (res.status == 200) {
                    console.log(res);
                    this.$emit('successEdit', false);
                    this.$refs.ruleForm.resetFields();
                    this.$message({
                      type: 'success',
                      message: '修改成功!',
                    });
                  }
                });
              } catch (error) {
                this.loading = false;
              }
            } else {
              // 新增
              try {
                voteAdd(objData).then(res => {
                  this.loading = false;
                  if (res.status == 200) {
                    console.log(res);
                    this.$emit('successEdit', false);
                    this.$refs.ruleForm.resetFields();
                    this.$message({
                      type: 'success',
                      message: '新建成功!',
                    });
                  }
                });
              } catch (error) {
                this.loading = false;
              }
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$emit('closeDrawer', false);
        if (this.isEdit) return;
        this.$refs[formName].resetFields();
      },
    },
  };
</script>

<style lang="scss" scoped>
  @import '~@/styles/mixin.scss';
  /deep/ .el-drawer__body {
    padding-left: 20px;
  }
  .draw-panel {
    /deep/.el-drawer {
      border-radius: 14px 0 0 14px;
    }
    /deep/.el-drawer__header {
      display: flex;
      align-items: center;
      @include font(16px, #34363b, bold);
      height: 60px;
      background: rgba(255, 255, 255, 1);
      box-shadow: 0px 1px 12px 0px rgba(194, 194, 198, 0.31);
      padding: 0 0 0 14px;
      margin-bottom: 0;
    }
    /deep/.el-drawer__body {
      padding: 0;
      box-sizing: border-box;
      overflow-y: auto;
      position: relative;
    }
    .detail-label {
      @include wh(100%, 51px);
      background-color: #f7f6f9;
      display: flex;
      align-items: center;
      @include font(14px, #6d6e6e, 800);
      padding-left: 14px;
      box-sizing: border-box;
    }
    .demo-ruleForm {
      width: 100%;
      .basic-detail {
        padding: 9px 30px 0 10px;
        box-sizing: border-box;
      }
      /deep/.el-form-item__label {
        @include font(14px, #7f848b, 400);
      }
      .full-input {
        @include wh(100%, 36px);
        border-radius: 7px;
        border: 1px solid #f4f0f3;
      }
      /deep/.el-date-editor {
        @include wh(190px, 36px);
        border-radius: 7px;
        border: 1px solid #f4f0f3;
      }
      .vote-time {
        @include wh(190px, 36px);
        position: relative;
        /deep/.el-input__inner {
          padding: 0 0 0 17px;
          border-radius: 7px;
          border: 1px solid #f4f0f3;
        }
        > i {
          position: absolute;
          right: 13px;
          top: 50%;
          transform: translateY(-50%);
          color: #979698;
        }
      }
      .jurisdType {
        padding-top: 10px;
        box-sizing: border-box;
        /deep/.el-form-item__label {
          width: 120px !important;
        }
        /deep/.el-form-item__content {
          margin-left: 120px !important;
        }
      }
      .el-textarea {
        border-radius: 7px;
        border: 1px solid #f4f0f3;
      }
      .option-list {
        .option-col {
          display: flex;
          align-items: center;
          justify-content: space-between;
          @include wh(86%, 37px);
          background: #fafafd;
          border-radius: 7px;
          @include font(14px, #1e2023, 400);
          margin-bottom: 14px;
          padding-left: 16px;
          box-sizing: border-box;
          > i {
            color: #b0b0b2;
            padding: 10px;
          }
        }
      }
      .option-row {
        display: flex;
        .full-input {
          width: 90%;
        }
        .add-btn {
          display: flex;
          @include wh(61px, 36px);
          justify-content: center;
          align-items: center;
          border-radius: 7px;
          border: 1px solid #d1e0f3;
          @include font(14px, #5a73c1, 500);
          margin-left: 9px;
        }
      }
    }
  }
  .save-btn {
    display: flex;
    justify-content: flex-end;
    padding-right: 30px;
    box-sizing: border-box;
    margin-top: 20px;
    .settbtn {
      @include wh(100px, 40px);
      background: #fffeff;
      border-radius: 7px;
      border: 1px solid #e8e4e8;
      @include font(14px, #353739, 400);
      &.savebtn {
        background-color: #3771e9;
        color: #fff;
      }
    }
  }
  /deep/.el-checkbox__input.is-checked .el-checkbox__inner {
    border-radius: 50%;
    background-color: #3770eb;
    border-color: #3770eb;
  }
  /deep/.el-checkbox__inner {
    border-radius: 50%;
  }
</style>
